package com.stu.test.servlet;

import com.stu.test.entity.Address;
import com.stu.test.mapper.IAddressMapper;
import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.InputStream;
import java.util.Arrays;
import java.util.List;

/**
 * ClassName: AddressSelectServlet
 * Package: com.stu.test.servlet
 * Description: @Version 1.0
 */
//webservlet中的路由不能重复，否则会报错：路由已存在
@WebServlet("/addAddrByBatch")
public class AddressAddByBatchServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        String resource = "mybatis-config.xml";
        // 读取总配置文件
        InputStream inputStream = Resources.getResourceAsStream(resource);
        // 获取session工厂
        SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
        // 获取session
        SqlSession session = sqlSessionFactory.openSession();

        Address address1=new Address();
        address1.setAddr("广州");
        address1.setPhone("644644");
        address1.setPostcode("3333");
        address1.setUserId(3);
        Address address2=new Address();
        address2.setAddr("上海");
        address2.setPhone("1110000");
        address2.setPostcode("666");
        address2.setUserId(4);
        Address address3=new Address();
        address3.setAddr("重庆");
        address3.setPhone("64646482");
        address3.setPostcode("444");
        address3.setUserId(5);
        List<Address> addressList= Arrays.asList(address1,address2,address3);
        int i = session.getMapper(IAddressMapper.class).addAddrBatch(addressList);
//        System.out.println("添加了"+i+"行数据");
        session.commit();

    }
}
